﻿using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reactive.Concurrency;
using System.Reactive.Linq;
using System.Threading;
using System.Windows;
using System.Windows.Threading;
using Caliburn.Micro;
using MyWpf.AppCommon;
using MyWpf.Entities;
using MyWpf.Providers;
using MyWpf.SysCommon;

namespace MyWpf.Components.MarketPrices
{
    public class MarketPriceViewModel : BaseManagerViewModel
    {
        private readonly IMarketPriceProvider _marketPriceProvider;
        private readonly EventLoopScheduler _scheduler;


        private ObservableCollection<MarketPrice> _marketPrices;
        public ObservableCollection<MarketPrice> MarketPrices
        {
            get => _marketPrices;
            set => this.SetProperty(ref _marketPrices, value);
        }

        public MarketPriceViewModel(IWindowManager windowManager, IMarketPriceProvider marketPriceProvider) : base(windowManager)
        {
            MarketPrices = new ObservableCollection<MarketPrice>();

            _scheduler = new EventLoopScheduler(t => new Thread(t)
            {
                Name = $"ObservableDataProvider{DateTime.Now}",
                IsBackground = true
            });

            _marketPriceProvider = marketPriceProvider;

            OnStartToPublish();
        }

        public void OnStartToPublish()
        {
            _marketPriceProvider.MarketPrices.ToObservable().ObserveOn(_scheduler).Subscribe(OnMarketPriceUpdate);
        }

        private void OnMarketPriceUpdate(MarketPrice marketPrice)
        {
            var row = MarketPrices.FirstOrDefault(t => t.ProductId.Equals(marketPrice.ProductId));

            if (row == null)
            {
                Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new System.Action(() =>
                {
                    MarketPrices.Add(marketPrice);
                }));
            }
        }
    }
}
